#include "hashMap_int.h"

HashMap_int* create_hashmap_int()
{
	return (HashMap_int*)calloc(1,sizeof(HashMap_int));
}
void destroy_hashmap_int(HashMap_int* map)
{
	//释放结点
	for (int i = 0; i < N; i++)
	{
		Entry_int* curr = map->table[i];
		while (curr != NULL)
		{
			Entry_int* next = curr->next;
			free(curr);
			curr = next;
		}
	}
	free(map);
}

V hashmap_get_int(HashMap_int* map, K key)
{
	int idx = hash_int(key);
	//遍历链表
	Entry_int* curr = map->table[idx];
	while (curr != NULL) {
		if (curr->key == key)
		{
			return curr->val;
		}
		curr = curr->next;
	}
	return -1;
}

V hashmap_put_int(HashMap_int* map, K key, V val)
{
	int idx = hash_int(key);
	//遍历链表
	Entry_int* curr = map->table[idx];
	while (curr != NULL )
	{
		if (curr->key == key)
		{
			V oldval = curr->val;
			curr->val = val;
			return oldval;
		}
		curr = curr->next;
	}
	Entry_int* entry = (Entry_int*)malloc(sizeof(Entry_int));
	if (entry == NULL)
	{
		printf("error\n");
		exit(1);
	}
	entry->key = key;
	entry->val = val;
	//头插法
	entry->next = map->table[idx];
	map->table[idx] = entry;
	
	return -1;
}

V hashmap_delete_int(HashMap_int* map, K key)
{
	int idx = hash_int(key);
	//遍历链表
	Entry_int* curr = map->table[idx];
	Entry_int* pre = NULL;
	while (curr != NULL)
	{
		if (curr->key == key)
		{
			//删除该结点
			if (pre == NULL)
			{
				map->table[idx] = curr->next;
			}
			else
			{
				pre->next = curr->next;
			}
			int deleteVal = curr->val;
			free(curr);
			return deleteVal;
		}
		pre = curr;
		curr = curr->next;
	}
	return -1;
}

int hash_int(K key)
{
	/*。。。*/
	//return h % N;//范围为0~N所以对N取模。
	int addr = abs(key) % N;
    return addr;
}